#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.biz.helper;



import ${package}.biz.config.AppConfig;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.fop.ImageInfo;
import com.qiniu.api.fop.ImageInfoRet;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * Created by well on 15/9/9.
 */
public class QiniuUpload {

    private final static Logger log = LoggerFactory.getLogger(QiniuUpload.class);

    private final static String IMG_TMP = System.getProperty("user.home")+File.separator + "tmp" +File.separator;

    private final static String ACCESS_KEY = "PGViS6CQJhAax6qo358RsBMR_W4K4aNgrK4iUqAw";

    private final static String SECRET_KEY = "3hYUh0kA3ooolMow1PiuSNAuPA5uk-2H8le5sTMZ";

    private final static String DEFAULT_BUCKET_NAME = AppConfig.getQiniuBucketName();


    static{
        File f = new File(IMG_TMP);
        if(!f.exists()){
            f.mkdirs();
        }
        File ff = new File(IMG_TMP+File.pathSeparator);
        if(!ff.exists()){
            ff.mkdirs();
        }
    }

    public static String getSecretKey(){
        return SECRET_KEY;
    }

    public static String getAccessKey(){
        return ACCESS_KEY;
    }

    public static String getUploadToken(){
        PutPolicy putPolicy = new PutPolicy(AppConfig.getQiniuBucketName());
        try {
            return putPolicy.token(getMac());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getUploadToken(String fileName){
        PutPolicy putPolicy = new PutPolicy(AppConfig.getQiniuBucketName()+":"+fileName);
        try {
            return putPolicy.token(getMac());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Mac getMac() {
        Mac mac = new Mac(QiniuUpload.getAccessKey(), QiniuUpload.getSecretKey());
        return mac;
    }

    public static String uploadFile(FileItem fileItem) {
        String extension = getExtension(fileItem);

        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;

        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(DEFAULT_BUCKET_NAME);
        String upToken = null;
        StringBuilder buff = new StringBuilder();
        String key = UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(fileItem.getInputStream(), IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);
            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            buff.append(ret.getKey());
        } catch (Exception e) {
            log.error("upload img error",e);
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return buff.toString();
    }


    public static String uploadAttachFile(FileItem fileItem) throws UnsupportedEncodingException {
        String name = URLEncoder.encode(fileItem.getName(), "utf-8");
        String extension = getExtension(fileItem);

        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;

        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(DEFAULT_BUCKET_NAME);
        String upToken = null;
        StringBuilder buff = new StringBuilder();
        String key = UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(fileItem.getInputStream(), IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);
            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            buff.append(ret.getKey()+"_"+name);
        } catch (Exception e) {
            log.error("upload img error",e);
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return buff.toString();
    }

    public static String uploadFilePng(byte[] bytes) {
        String extension = ".png";
        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        String bucketName = "maihaoche";
        PutPolicy putPolicy = new PutPolicy(bucketName);
        String upToken = null;
        StringBuilder sb = new StringBuilder();
        String key = UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(bytes, IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);

            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            sb.append(ret.getKey());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return sb.toString();
    }


    public static String uploadFile(byte[] bytes) {//上传图片
        String extension = ".jpg";
        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(DEFAULT_BUCKET_NAME);
        String upToken = null;
        StringBuilder sb = new StringBuilder();
        String key = UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(bytes, IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);
            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            sb.append(ret.getKey());
        } catch (Exception e) {
            log.error("upload img error", e);
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return sb.toString();
    }


    public static String uploadLicenceFile(byte[] bytes) {//上传图片
        String extension = ".jpg";
        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(DEFAULT_BUCKET_NAME);
        String upToken = null;
        StringBuilder sb = new StringBuilder();
        String key =UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(bytes, IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);
            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            sb.append(ret.getKey());
        } catch (Exception e) {
            log.error("upload img error", e);
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return sb.toString();
    }

    public static String uploadFileByExt(FileItem fileItem) {
        String extension = getExtension(fileItem.getName());
        Config.ACCESS_KEY = ACCESS_KEY;
        Config.SECRET_KEY = SECRET_KEY;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        PutPolicy putPolicy = new PutPolicy(DEFAULT_BUCKET_NAME);
        String upToken = null;
        StringBuilder sb = new StringBuilder();
        String key = UUID.randomUUID().toString().toUpperCase() + extension;
        try {
            upToken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            saveTmp(fileItem.getInputStream(), IMG_TMP + key);
            PutRet ret = IoApi.putFile(upToken, key, IMG_TMP + key, extra);
            if (StringUtils.isEmpty(ret.getKey())) {
                return "";
            }
            sb.append(ret.getKey());
        } catch (Exception e) {
            log.error("upload img error", e);
        } finally {
            deleteTmp(IMG_TMP + key);
        }
        return sb.toString();
    }

    public static Map getSize(String url) {
        Map m = new HashMap();
        ImageInfoRet ret = ImageInfo.call(url);
        m.put("height", ret.height);
        m.put("width", ret.width);
        return m;
    }

    /**
     * 根据文件名 获取文件的后缀名
     *
     * @param fileItem
     * @return
     */
    private static String getExtension(FileItem fileItem) {
        String name = fileItem.getName();
        String type = ".jpg";
        if (name.contains(".")) {
            type = name.substring(name.lastIndexOf("."), name.length());
        }
        return type;
    }

    /**
     * 根据文件名 获取文件的后缀名
     *
     * @param fileUrl
     * @return
     */
    private static String getExtension(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return ".jpg";
        }
        return fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length());
    }


    private static void saveTmp(InputStream is, String fileName) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        FileOutputStream fileOutStream = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }

            byte[] data = outStream.toByteArray();
            File imageFile = new File(fileName);

            fileOutStream = new FileOutputStream(imageFile);
            fileOutStream.write(data);
        } catch (IOException e) {
            log.error("upload img error",e);
        } finally {
            if (fileOutStream != null) {
                try {
                    fileOutStream.close();
                } catch (IOException e) {
                }
            }
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    private static void saveTmp(byte[] bytes, String fileName) {
        FileOutputStream fileOutStream = null;
        try {
            File imageFile = new File(fileName);
            fileOutStream = new FileOutputStream(imageFile);
            fileOutStream.write(bytes);
        } catch (IOException e) {
            log.error("upload img error",e);
        } finally {
            if (fileOutStream != null) {
                try {
                    fileOutStream.close();
                } catch (IOException e) {
                }
            }

        }
    }


    private static void deleteTmp(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }
}
